<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Enrollment Summary</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/student-system.css" /> 
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	
	<script>
		$(document).ready(function(){
			course_id = new Array();
		
			 $("#result_div").hide();
			 
		 	 $("button").click(function(){
		 	
		 		 var select = document.getElementById("department_in");
				 var department_in = select.options[select.selectedIndex].value;
				 
				 var select1 = document.getElementById("year_in");
				 var year_in = select1.options[select1.selectedIndex].value;
				 
				 var select2 = document.getElementById("school_year_in");
				 var school_year_in = select2.options[select2.selectedIndex].value;
				 
				 var select3 = document.getElementById("term_in");
				 var term_in = select3.options[select3.selectedIndex].value;
				
				 
				 //alert("department_in:"+department_in+"|year_in:"+year_in+"|school_year_in:"+school_year_in+"|term_in:"+term_in);
	 		 
		 		 var department_is_null = 1; //1 for null
		 		 var year_is_null  = 1;
		 		 var school_year_is_null = 1;
		 		 var term_is_null  = 1;
		 		 
		 		 var start_date;
		 		 var year;
		 		// var year_high = false;
		 		 
		 		 if(department_in=="select"){
		 			
		 		 }else{
		 			department_is_null = 0;		 			
		 		 }
		 		 
		 		 if(year_in=="select"){
		 			
		 		 }else{
		 			year_is_null = 0;
		 			 
		 			var date_now = new Date();
		 			var temp_year  = date_now.getFullYear();
		 			var temp_month = date_now.getMonth()+1;
		 			
		 			switch (year_in){
						case "1":
					
							if(temp_month<6)
							{
								start_date = temp_year-1;
							}else{
								start_date = temp_year ;  
							}
							break;
						
						case "2":
					
							if(temp_month<6){
								
								start_date = temp_year-2;
							}else{
								start_date = temp_year-1;
								
							}			
							break;
						
						case "3":
						
							if(temp_month<6){
								
								start_date = temp_year-3;
							}else{
								start_date = temp_year-2;
								
							}
							break;
						
						case "4":
						
							if(temp_month<6){
								
								start_date = temp_year-4;
							}else{
								start_date = temp_year-3;
								
							}	
							break ;
						
				/*		case "5":
							
							if(temp_month<6){
								
								start_date = temp_year-4;
							}else{
								start_date = temp_year-3;
								
							}
							
							year_high = true;
							
						break;	
				*/
		 		 	}
		 		 }
		 			
		 		 if(school_year_in=="select"){
		 			
		 		 }else{
		 			school_year_is_null = 0;
		 			
		 			if(temp_month<6){
		 				year = parseInt(start_date) + parseInt(school_year_in)-1;
		 			}
		 			else{
		 				year = parseInt(start_date) + parseInt(school_year_in);
		 			} 			
		 		 }
		 		 
		 		 if(term_in=="select"){
		 			
		 		 }else{
		 			term_is_null = 0;
		 		 }
		 		 
		 		 if(department_is_null+year_is_null+school_year_is_null+term_is_null != 0)
		 		 {
		 			 	alert("กรุณาใส่ keyword ในการค้นหาให้ครบค่ะ");		 
		 			 	return false;
		    	 }
		 		 
		 		 //alert(department_in +" "+ start_date +" "+ year +" "+ term_in);
		 		
				/* AJAX */
			  	var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {	
						//alert("I'm Back");//////////////////
						
						//alert($('#result_div').find('div').length);//////////////////
						//alert($('#result_div').find('table').length);//////////////////
						
						//clear array course_id
						course_id.length = 0; 
						
						if($('#result_div').find('div').length > 0) {								
							$('#result_div').find('div').remove();
						}
						
						var jsonObj = JSON.parse(xmlhttp.responseText);
						
						if(jsonObj.length == 0) {
							alert("ไม่พบข้อมูล");
						}
						else{
							//alert("That work !!!");///try///
							
							
							head = '<div class="CSSTableGenerator" id="test">'
									+ '<table  width="950" border="1" align="center" id="summary">'
									+ '<tr>'
									+ '<td style="text-align: center;">ชื่อ-สกุล</td>' ;
									
							//$('#result_div').append(head);
						
							for(i in jsonObj) {
	
								head = head + '<td width="80"><center>'+jsonObj[i].courseId+'</center></td>';
								
								course_id.push(jsonObj[i].courseId);
							}
							
							head = head + '</table></div>';
							
							$('#result_div').append(head);
							$("#result_div").show();

						  	show_summary_detail(department_in, start_date, year, term_in);
						  	
						}
											
					}// end if check state
				}// end function
				
				parameter = "department="+department_in+"&start_date="+start_date+"&year="+year+"&term="+term_in;
				
				//alert(parameter);/////////////////////////////////try///////////////////////////
				
				xmlhttp.open("POST", "search_coursename_summary.jsp?"+parameter, true);
				xmlhttp.send();
		 	
		  });
		 	 
		});
		
		function show_summary_detail(department, start_date, year, term) {
			/* AJAX */
		  	var xmlhttp;
			
			if(window.XMLHttpRequest) {
				// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp = new XMLHttpRequest();
			}
			else {
				// code for IE6, IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			
			xmlhttp.onreadystatechange = function() {
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {	
					//alert("I'm Back");//////////////////
					
					var jsonObj = JSON.parse(xmlhttp.responseText);
					
					if(jsonObj.length == 0) {
						alert("ไม่พบข้อมูล");
					}
					else{
						//alert("That work !!!");///try///

						var student_id = ""; 
						var text = '';
						
						for(i in jsonObj) {
							//alert("i "+i);////////////////////
							
							if(i%2 == 0) { 
								class_name = 'silvergrad';
							}
							else {
								class_name = 'bluegrad';
							}
							
							//alert("student_id="+student_id+"  jsonObj[i].student_i="+jsonObj[i].student_id+"  check != "+(student_id != jsonObj[i].student_id));////try////
							
							if(student_id != jsonObj[i].student_id) {
								student_id = jsonObj[i].student_id;
								text = '';
								
								text = text + '<tr class="'+class_name+'">'
									+ '<td>'+ jsonObj[i].student_name +' ' +jsonObj[i].student_surname  + '</td>';
									
								//alert("course id length "+course_id.length);////////////////////////////////
							
								for(j=0; j<course_id.length; j++) {
									text = text + '<td  stlye="text-align: center;" id="'+jsonObj[i].student_id+course_id[j]+'"><center> - </center></td>';
								}
								
								text = text + '</tr>';
								
								//alert(text);////////////////////////////////
								
								$('#summary').append(text);
								
								
							}
								
							$('#'+jsonObj[i].student_id+jsonObj[i].course_id).text(jsonObj[i].grade);
														
						}
					  	
					}
										
				}// end if check state
			}// end function
			
			parameter = "department="+department+"&start_date="+start_date+"&year="+year+"&term="+term;
			
			//alert(parameter);//try//
			
			xmlhttp.open("POST", "search_enroll_summary.jsp?"+parameter, true);
			xmlhttp.send();
		}

	</script>
</head>
<body>

<%
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
	System.out.println("@student_home");	
	
	//get permission 
	
	String name = String.valueOf(session.getAttribute("name"));
	String surname = String.valueOf(session.getAttribute("surname"));
	String role_name = String.valueOf(session.getAttribute("enrollment_role"));
	
	String department_id = String.valueOf(session.getAttribute("department_id"));

	
			
	System.out.println("name : " + name);///////////////////////////////
	System.out.println("department_id : " + department_id);/////////////////////////
	
	
	List<String> system_name = new ArrayList<String>();
	
	Permission permission = new Permission(strUser,name);
	permission.setDepartmentId(department_id);
	permission.setRegisCreate(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_create"))));
	permission.setRegisDelete(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_delete"))));
	permission.setRegisRead(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_read"))));
	permission.setRegisUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("enrollment_update"))));
	
	//check permission
	if(!permission.getRegisRead()){%>
		<script>alert("This user dont have PERMISSION to access this zone.");</script>
		<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=enroll_home.jsp"> 	
	<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	
	/* find department in database */
	List<Department> department = new ArrayList<Department>();
	
	try {			   
		ResultSet rs_department;
		if(("0").equals(permission.getDepartment_id()))
		{
			  rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
						+ " FROM department " + " ORDER BY department_id");
		}
		else{
			
			
			  rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
						+ " FROM department " 
					    +" WHERE department_id="+permission.getDepartment_id()
					    );
		}
		
		while(rs_department.next()) {
			Department dep = new Department();
			
			dep.setDepartmentNameTH(rs_department.getString("department_name_th"));
			dep.setDepartmentId(Integer.parseInt(rs_department.getString("department_id")));
			
			department.add(dep);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	connect.close();
%>

<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
			<table border="0">
				<tr style="font-size:10px">
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="enroll_home.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">หน้าแรก</label></font></h2></a></center>
					</td>
<%
			if(permission.getRegisRead()) {
%>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="enroll_search.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">ค้นหา</label></font></h2></a></center>
					</td>
					<td width = "720" height="50" style= "background-color:#FFFFFF ; border-bottom-color: #FFFFFF; border-left-color: #FFFFFF">
						<center><h2><font color="#273b80"><label>สรุปผลการลงทะเบียน</label></font></h2></center>
					</td>
<%
			}
			if(permission.getRegisCreate()) {
%>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="enroll_enrollment.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">ลงทะเบียนรายวิชา</label></font></h2></center>
					</td>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="enroll_timetable.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">ตารางสอน</label></font></h2></a></center>
					</td>
<%
			}
			
%>
				</tr>
			</table>
				
				<div id="main-content-ac">					
						</br></br>
						
					<center>
					
						  <div style="font-size:15px;">
						  	<center>	
								  <font size="5"> ภาควิชา <select name="department_in" id="department_in" style="font-size:15px;">
								  			<option value="select">Select</option>	 
<%
										for(Department dept : department) {
											if(dept.getDepartmentId() == 0) {}
											else {
%>
												<option value="<%=dept.getDepartmentId()%>" id="<%=dept.getDepartmentId()%>"><%=dept.getDepartmentNameTH()%></option>	
<%												
											}
										}
%>
										</select>
										
								  &nbsp; ชั้นปี <select name="year_in" id="year_in" style="font-size:15px;">
								  			<option value="select">Select</option>
								  			<option value="1"> 1 </option>
								  			<option value="2"> 2 </option>
								  			<option value="3"> 3 </option>
								  			<option value="4"> 4 </option>
								  <!-- 			<option value="5"> ปีสูง </option>		 -->
								  	   </select> 
							  	   
							  	  &nbsp;  ปีการศึกษา <select name="school_year_in" id="school_year_in" style="font-size:15px;">
							  			<option value="select">Select</option>
							  			<option value="1"> 1 </option>
							  			<option value="2"> 2 </option>
							  			<option value="3"> 3 </option>
							  			<option value="4"> 4 </option>
							  	   </select> 
							  	   
							  	  &nbsp;  เทอม <select name="term_in" id="term_in" style="font-size:15px;">
							  			<option value="select">Select</option>
							  			<option value="1"> 1 </option>
							  			<option value="2"> 2 </option>
							  			<option value="3"> 3 </option>
							  		</select>
							  	</font>
								 <br>
								 <br>
								 <button style="height: 25px; width: 80px; font-size: medium; text-align: center;">ค้นหา</button>
								 <br><br>							 
							</center>
				  	  	</div>
				  	  
  					</center>
  					
  					<br><br>
  	 				
  					<div id="result_div">
	
	  				</div>
  											
						<br><br><br><br><br><br><br><br><br><br><br><br>
				
				
			<div style="clear: both;"></div>				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

</body>
</html>